package main

import (
	"fmt"
	"github.com/PuerkitoBio/goquery"
	"github.com/axgle/mahonia"
	"io"
	"io/ioutil"
	"net/http"
	"os"
	"path"
	"runtime"
	"strconv"
	"strings"
)

var spiderUrl = "https://www.1ppt.com"

var enc = mahonia.NewDecoder("gbk")

var filePath, _ = os.Getwd()

func main() {

	spiderBody, _ := http.Get(spiderUrl)

	body, _ := ioutil.ReadAll(spiderBody.Body)

	reader, _ := goquery.NewDocumentFromReader(strings.NewReader(enc.ConvertString(string(body))))

	// 获取列表
	tags := reader.Find(".col_nav").Find("a")

	var tagsMap map[int]string
	tagsMap = make(map[int]string)

	tags.Each(func(i int, selection *goquery.Selection) {

		attr, _ := selection.Attr("title")
		tagsMap[i] = strings.Replace(attr, "PPT", "", -1)
	})

	tagsMapNum := len(tagsMap)

	for i := 0; i < tagsMapNum; i++ {
		fmt.Print(strconv.Itoa(i) + "：" + tagsMap[i] + "    ")
		if i%5 == 0 && i != 0 {
			fmt.Println()
		}
	}

	fmt.Println()
	fmt.Println("请输入需要爬取的类型：")

	var scanInt int
	_, _ = fmt.Scanf("%d", &scanInt)

	fmt.Println("您输入的是：" + strconv.Itoa(scanInt) + "，将为您进行抓取")

	scanEl := tags.Get(scanInt)

	listHref := scanEl.Attr

	// 进入列表页分析
	analysisList(listHref[0].Val)

	fmt.Println("抓取完成。")
}

/**
分析列表页面
*/
func analysisList(href string) {

	spiderBody, _ := http.Get(spiderUrl + href)

	body, _ := ioutil.ReadAll(spiderBody.Body)

	reader, _ := goquery.NewDocumentFromReader(strings.NewReader(enc.ConvertString(string(body))))
	// 获取列表
	tags := reader.Find(".tplist").Find("li")

	tags.Each(func(i int, selection *goquery.Selection) {

		find := selection.Find("a").First()

		attr, _ := find.Attr("href")

		split := strings.Split(attr, "/")[2]

		id := strings.Replace(split, ".html", "", 1)

		download(id)

	})

	// 分析是否下一页
	next := reader.Find(".pages").Find("a")

	next.Each(func(i int, selection *goquery.Selection) {
		text := selection.Text()
		if strings.Contains(text, "下一页") {
			hrefNext, _ := selection.Attr("href")
			analysisList(hrefNext)
		}
	})

}

/**
进行链接下载
*/
func download(id string) {

	ppt := "https://www.1ppt.com/plus/download.php?aid=" + id

	spiderBody, _ := http.Get(ppt)

	defer spiderBody.Body.Close()

	body, _ := ioutil.ReadAll(spiderBody.Body)

	reader, _ := goquery.NewDocumentFromReader(strings.NewReader(enc.ConvertString(string(body))))
	// 获取列表
	downloadHref, _ := reader.Find(".c1").Find("a").Attr("href")

	res, _ := http.Get(downloadHref)

	defer res.Body.Close()

	filePathPPT := filePath + GetConLogPath("ppt")

	_, err := os.Stat(filePathPPT)
	if err != nil {
		if os.IsNotExist(err) {
			err := os.Mkdir(filePathPPT, os.ModePerm)
			fmt.Println("创建 PPT 文件夹")
			if err != nil {
				fmt.Printf("mkdir failed![%v]\n", err)
			}
		}
	}

	fileName := filePathPPT + path.Base(downloadHref)

	// 创建文件流
	file, _ := os.Create(fileName)

	defer func(file *os.File) {
		err := file.Close()
		if err != nil {

		}
	}(file)

	_, _ = io.Copy(file, res.Body)

	fmt.Println("成功下载文件：" + fileName)
}

/**
获取不同系统路径
*/
func GetConLogPath(path string) string {
	ostype := runtime.GOOS
	if ostype == "windows" {
		path = "\\" + path + "\\"
	} else if ostype == "linux" {
		path = "/" + path + "/"
	}
	return path
}
